<template>
    <div>
        <el-form class="" :inline="true" label-width="0" :model="formData" size="default" style="width: 100%">
            <el-form-item>
                <el-checkbox-group v-model="formData.range">
                    <el-checkbox-button label="public" value="public">公开题目</el-checkbox-button>
                    <!-- <el-checkbox-button label="user" value="user">用户题目</el-checkbox-button> -->
                    <el-checkbox-button label="match" value="match">精选题目</el-checkbox-button>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item>
                <el-input style="width: 160px;" clearable v-model.lazy="formData.name" placeholder="输入题目名或ID搜索">
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-cascader placeholder="输入知识点进行搜索" v-model="formData.label" :style="{ width: '100%' }"
                    :options="grouplabel" filterable
                    :props="{ checkStrictly: true, value: 'ID', label: 'name', expandTrigger: 'hover' }" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="start">搜索</el-button>
            </el-form-item>
        </el-form>
        <el-table class="" :data="tableData" height="75vh" style="width: 100%">
            <el-table-column prop="ID" label="ID" width="80"></el-table-column>
            <el-table-column prop="name" label="名称" show-overflow-tooltip width=""></el-table-column>
            <el-table-column prop="label" label="标签" show-overflow-tooltip width="">
                <template #default="{ row }">
                    <el-tag class="question-intable-label" text type="primary" effect="plain" size="default"
                        v-for="(v, key) in row.questionlabel" :key="`1-${key}`">
                        {{ getlabel.find(e => e.ID === v.labelid)?.name }}
                    </el-tag>
                </template>
            </el-table-column>
            <!-- <el-table-column prop="info" label="难度"></el-table-column> -->
            <el-table-column label="添加" width="80">
                <template #default="{ row }">
                    <el-button type="primary" :icon="Plus" @click="add(row)" />
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="pager" @current-change="handleCurrentChange" :page-size="Number(limit)"
            :page-sizes="pageSizes" @size-change="handleSizeChange" layout="total, sizes ,prev, pager, next"
            :total="totalCount">
        </el-pagination>
    </div>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref, watch } from 'vue';
import { useStore } from 'vuex';
import { asyncadminselectquestion, asyncSelectquestionblack, asyncUpdatequestionblack, Iobj } from '../../../../api';
import { Iquestion, Storekey } from '../../../../interface';
import Studycodemodel from '../../../../mysql_interface/studycodemodel';
import { findpid } from '../../../../util/code';

const store = useStore(Storekey)

const emit = defineEmits(['add-question']);
const p = defineProps<{ vipLabel: Studycodemodel.ILabel }>();

const vipLabel = computed(() => {
    return p.vipLabel
})

const getlabel = computed(() => {
    return store.state.label?.rows || [];
});
const grouplabel = computed(() => {
    const data = getlabel.value.filter((e) => e.type === "题目标签");
    return findpid(data ? data : []);
});

onMounted(() => { start() })

const formData = ref<Iobj<Studycodemodel.Iquestion>>({ name: "", label: "", range: ["public"] })
const limit = ref(20);
const pageSizes: number[] = [limit.value, 50, 100, 200,]
const offset = ref(0);
const tableData = ref<Studycodemodel.Iquestion[]>([])
const totalCount = ref(0)
const query = computed(() => {
    let _like: [keyof Studycodemodel.Iquestion, string | number] | undefined;
    const obj: Iobj<Iquestion> = {
        // range: ["match", "public"],
        type: "代码",
        _order: ["rating", "ID"],
        _sortable: "ASC",
        _limit: Number(limit.value),
        _offset: Number(offset.value),
    };
    if (formData.value.range?.length) {
        obj.range = formData.value.range;
    }
    if (formData.value.name) {
        _like = ['name', formData.value.name];
    }
    if (formData.value.label?.length) {
        obj._include = { questionlabel: ["labelid", formData.value.label] }
    }
    obj._like = _like;
    return obj;
});
watch(query, v => { start() })
async function start() {
    console.log(query.value)
    const { count, rows } = await asyncadminselectquestion(query.value) // admin 接口
    tableData.value = rows
    totalCount.value = count
}
function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
    start()
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}

const add = async (row: Studycodemodel.Iquestion) => {
    try {
        // check
        const { count, rows } = await asyncSelectquestionblack({
            questionid: row?.ID,
            labelid: vipLabel.value.ID,
        })
        if (count) {
            ElMessage({ message: `题目：${row.name} 已存在，无需重复添加`, type: "warning", });
            return
        }
        await asyncUpdatequestionblack({
            questionid: row?.ID,
            labelid: vipLabel.value.ID,
        });
        ElMessage({ message: "添加成功", type: "success", });
        // 发出添加题目事件，通知父组件
        emit('add-question');
    } catch (e) {
        ElMessage({ message: String(e), type: "error", });
    }
}

</script>

<style scoped></style>